<!-- 添加建筑 -->
<template>
  <div>
    <el-dialog :visible.sync="dialogVisible" :before-close="handleCloseBindWarnStandard" :close-on-click-modal="false" :title="title" width="935px" height="300px">
      <!-- :validate-on-rule-change="false"  -->
      <el-form v-loading="formLoading" ref="dialogForm" :model="dialogForm" :rules="rules" label-width="120px" class="twoColumn">
        <el-form-item label="所属建筑群">
          <el-input v-model="dialogForm.park_name" class="el-disabled" readonly="readonly"/>
        </el-form-item>
        <el-form-item label="建筑名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入建筑名称" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="危险系数" prop="danger_classes">
          <el-select v-model="dialogForm.danger_classes" class="filter-item" placeholder="请选择危险系数">
            <el-option v-for="(key, value) in riskLevel" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="建筑类型" prop="building_type">
          <el-select v-model="dialogForm.building_type" class="filter-item" placeholder="请选择建筑类型">
            <el-option v-for="(key, value) in buildType" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="地区/详细地址" prop="address" class="regionAddCombination">
          <el-cascader
            :options="options"
            v-model="selectedOptions"
            :props="optionProps"
            size="large"
            filterable
            clearable
            @change="handleChange" />
          <i>-</i>
          <el-input v-model="dialogForm.address" placeholder="请输入详细地址" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="建筑用途" prop="building_property">
          <el-select v-model="dialogForm.building_property" class="filter-item" placeholder="请选择建筑用途">
            <el-option v-for="(key, value) in buildPurpose" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="建筑高度" prop="storey_height">
          <el-input v-model="dialogForm.storey_height" placeholder="请输入建筑高度" >
            <template slot="append">m</template>
          </el-input>
        </el-form-item>
        <el-form-item label="建筑结构" prop="structure">
          <el-select v-model="dialogForm.structure" class="filter-item" placeholder="请选择建筑结构">
            <el-option v-for="(key, value) in buildingStructure" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="地上面积" prop="above_ground_area">
          <el-input v-model="dialogForm.above_ground_area" placeholder="请输入地上面积">
            <template slot="append">㎡</template>
          </el-input>
        </el-form-item>
        <el-form-item label="地下面积" prop="under_ground_area">
          <el-input v-model="dialogForm.under_ground_area" placeholder="请输入地下面积">
            <template slot="append">㎡</template>
          </el-input>
        </el-form-item>
        <el-form-item label="地上层数" prop="above_ground_floor">
          <el-input :disabled="dialogType==='修改'" v-model="dialogForm.above_ground_floor" placeholder="请输入地上层数">
            <template slot="append">层</template>
          </el-input>
        </el-form-item>
        <el-form-item label="地下层数" prop="under_ground_floor">
          <el-input :disabled="dialogType==='修改'" v-model="dialogForm.under_ground_floor" placeholder="请输入地下层数">
            <template slot="append">层</template>
          </el-input>
        </el-form-item>
        <el-form-item label="防火等级" prop="fireproof_endurance_rating">
          <el-select v-model="dialogForm.fireproof_endurance_rating" class="filter-item" placeholder="请选择防火等级">
            <el-option v-for="(key, value) in refractoryLevel" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="建筑年代" prop="year_built">
          <el-date-picker
            v-model="dialogForm.year_built"
            value-format="yyyy-MM-dd"
            type="year"
            placeholder="选择建筑年代"/>
        </el-form-item>
        <el-form-item label="验收日期" prop="acceptance_at">
          <el-date-picker
            v-model="dialogForm.acceptance_at"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择验收日期"/>
        </el-form-item>
        <el-form-item label="所在经纬度" prop="latitude" class="mapInfo">
          <el-input v-model="dialogForm.longitude" placeholder="请输入经度" autocomplete="off"/>
          <el-input v-model="dialogForm.latitude" placeholder="请输入纬度" autocomplete="off"/>
          <i class="el-icon-location-outline" @click="manualPickup"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleMap" title="手动拾取" width="600px" height="400px">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px">
        <el-form-item label="所在经纬度" class="mapInfo-map">
          <el-input v-model="dialogForm.longitude" placeholder="请输入经度" autocomplete="off"/>
          <el-input v-model="dialogForm.latitude" placeholder="请输入纬度" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="地区/详细地址">
          <el-input v-model="dialogForm.address" placeholder="请输入详细地址" autocomplete="off"/>
        </el-form-item>
        <div id="container" style="width:560px;height:300px;"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisibleMap = false">确 定</el-button>
        <el-button @click="dialogVisibleMap = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { buildAdd, buildUpdate } from '@/api/park'
import { parseTime } from '@/utils/index'
import { getRegion } from '@/api/common'
import AMap from 'AMap'

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    dialogForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogType: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      title: '',
      options: [],
      optionProps: {
        value: 'area_id',
        label: 'area_name',
        children: 'list'
      },
      selectedOptions: [],
      requestFn: {},
      address: '',
      // 添加form验证
      rules: {
        name: [{
          required: true,
          message: '请输入建筑名称',
          trigger: 'blur'
        }],
        danger_classes: [{
          required: true,
          message: '请选择危险系数',
          trigger: 'change'
        }],
        building_type: [{
          required: true,
          message: '请选择建筑类型',
          trigger: 'change'
        }],
        address: [{
          required: true,
          message: '请输入详细地址',
          trigger: 'blur'
        }],
        building_property: [{
          required: true,
          message: '请选择建筑用途',
          trigger: 'change'
        }],
        storey_height: [{
          required: true,
          message: '请输入建筑高度',
          trigger: 'blur'
        }],
        structure: [{
          required: true,
          message: '请选择建筑结构',
          trigger: 'change'
        }],
        above_ground_area: [{
          required: true,
          message: '请输入地上面积',
          trigger: 'blur'
        }],
        under_ground_area: [{
          required: true,
          message: '请输入地下面积',
          trigger: 'blur'
        }],
        above_ground_floor: [{
          required: true,
          message: '请输入地上层数',
          trigger: 'blur'
        }],
        under_ground_floor: [{
          required: true,
          message: '请输入地下层数',
          trigger: 'blur'
        }],
        fireproof_endurance_rating: [{
          required: true,
          message: '请选择防火等级',
          trigger: 'change'
        }],
        year_built: [{
          required: true,
          message: '请选择建筑年代',
          trigger: 'change'
        }],
        acceptance_at: [{
          required: true,
          message: '请选择验收日期',
          trigger: 'change'
        }],
        latitude: [{
          required: true,
          message: '请选择所在经纬度',
          trigger: 'blur'
        }]
      },
      formLoading: false,
      // 地图
      dialogVisibleMap: false,
      riskLevel: this.GLOBAL.riskLevel,
      buildType: this.GLOBAL.buildType,
      buildPurpose: this.GLOBAL.buildPurpose,
      buildingStructure: this.GLOBAL.buildingStructure,
      refractoryLevel: this.GLOBAL.refractoryLevel
    }
  },
  watch: {
    dialogType(val) {
      if (val === '添加') {
        this.title = '添加建筑'
        this.requestFn = buildAdd
      }
      if (val === '修改') {
        this.title = '修改建筑'
        this.requestFn = buildUpdate
      }
    },
    dialogForm(val) {
      if (val.year_built) {
        val.year_built = parseTime(val.year_built * 1000, '{y}-{m}-{d}')
      }
      if (val.acceptance_at) {
        val.acceptance_at = parseTime(val.acceptance_at * 1000, '{y}-{m}-{d}')
      }
      this.dialogForm = val
      if (this.dialogType === '修改') {
        this.selectedOptions = []
        this.selectedOptions.push(this.dialogForm.province + '')
        this.selectedOptions.push(this.dialogForm.city + '')
        this.selectedOptions.push(this.dialogForm.district + '')
      }
    }
  },
  created() {
    this.init()
    this.getRegion()
  },
  methods: {
    init() {
      if (this.dialogType === '添加') {
        this.title = '添加建筑'
        this.requestFn = buildAdd
      }
      if (this.dialogType === '修改') {
        this.title = '修改建筑'
        this.requestFn = buildUpdate
        this.selectedOptions.push(this.dialogForm.province + '')
        this.selectedOptions.push(this.dialogForm.city + '')
        this.selectedOptions.push(this.dialogForm.district + '')
      }
    },
    initMap() {
      var that = this
      const map = new AMap.Map('container', {
        center: [116.397428, 39.90923],
        resizeEnable: true,
        zoom: 10
      })
      var geocoder = new AMap.Geocoder()
      var address = ''
      var cityList = []
      var districtList = []
      that.options.forEach(function(value, index, array) {
        if (array[index].area_id === that.dialogForm.province) {
          address += array[index].area_name
          cityList = array[index].list
        }
      })
      cityList.forEach(function(value, index, array) {
        if (array[index].area_id === that.dialogForm.city) {
          address += array[index].area_name
          districtList = array[index].list
        }
      })
      districtList.forEach(function(value, index, array) {
        if (array[index].area_id === that.dialogForm.district) {
          address += array[index].area_name
        }
      })
      address += that.dialogForm.address
      this.address = address
      geocoder.getLocation(address, function(status, result) {
        if (status === 'complete' && result.geocodes.length) {
          map.clearMap()
          var marker = new AMap.Marker()
          var lnglat = result.geocodes[0].location
          that.dialogForm.longitude = lnglat.lng
          that.dialogForm.latitude = lnglat.lat
          marker.setPosition(lnglat)
          marker = new AMap.Marker({
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            position: lnglat
          })
          map.add(marker)
          map.setFitView(marker)
        } else {
          that.$message({
            message: '根据地址查询位置失败',
            type: 'warning'
          })
        }
      })
      AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function() {
        map.addControl(new AMap.ToolBar())
        map.addControl(new AMap.Scale())
      })
      var oldLng = that.dialogForm.longitude
      var oldLat = that.dialogForm.latitude
      var marker
      if (oldLng !== '' && oldLat !== '') {
        marker = new AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position: [oldLng, oldLat]
        })
        map.add([marker])
        map.setFitView()
      }
      map.on('click', function(e) {
        const { lng, lat } = e.lnglat
        // 先删除上个标注
        var oldLng = that.dialogForm.longitude
        var oldLat = that.dialogForm.latitude
        var marker
        if (oldLng !== '' && oldLat !== '') {
          map.clearMap()
        }
        var address
        that.dialogForm.longitude = lng
        that.dialogForm.latitude = lat
        marker = new AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position: [that.dialogForm.longitude, that.dialogForm.latitude]
        })
        map.add([marker])
        map.setFitView()
        // 这里通过高德 SDK 完成。
        var geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: 'base'
        })
        // 设置label标签
        geocoder.getAddress([that.dialogForm.longitude, that.dialogForm.latitude], function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              var addr = result.regeocode.addressComponent
              // 具体地址
              that.dialogForm.address = addr.township + addr.street + addr.streetNumber
              // 省
              that.dialogForm.province = result.regeocode.addressComponent.province
              // 市
              that.dialogForm.city = result.regeocode.addressComponent.city === '' ? that.dialogForm.province : result.regeocode.addressComponent.city
              // 区
              that.dialogForm.district = result.regeocode.addressComponent.district
              address = that.dialogForm.province + that.dialogForm.city + that.dialogForm.district + that.dialogForm.address
              that.address = address
              // 回填下拉框
              that.selectedOptions = []
              var cityList = []
              var districtList = []
              if (that.dialogForm.province !== '') {
                that.options.forEach(function(value, index, array) {
                  if (array[index].area_name === that.dialogForm.province) {
                    that.selectedOptions.push(array[index].area_id)
                    cityList = array[index].list
                  }
                })
                cityList.forEach(function(value, index, array) {
                  if (array[index].area_name === that.dialogForm.city) {
                    that.selectedOptions.push(array[index].area_id)
                    districtList = array[index].list
                  }
                })
                districtList.forEach(function(value, index, array) {
                  if (array[index].area_name === that.dialogForm.district) {
                    that.selectedOptions.push(array[index].area_id)
                  }
                })
              }
              that.$nextTick()
            }
          } else {
            that.$message({
              message: '地址获取失败',
              type: 'warning'
            })
          }
        })
      })
    },
    handleChange(val) {
      if (val.length > 0) {
        this.dialogForm.province = val[0]
        this.dialogForm.city = val[1]
        this.dialogForm.district = val[2]
      } else {
        this.selectedOptions = []
        this.dialogForm.province = ''
        this.dialogForm.city = ''
        this.dialogForm.district = ''
      }
    },
    submitForm(val) {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const that = this
          var params = {
            ...that.dialogForm
          }
          if (that.selectedOptions) {
            params.province = that.selectedOptions[0]
            params.city = that.selectedOptions[1]
            params.district = that.selectedOptions[2]
          }
          if (params.is_forbidden) {
            delete params['is_forbidden']
          }
          that.requestFn(params)
            .then((res) => {
              that.formLoading = false
              const data = res.data
              if (data.code === 40000) {
                that.$message.success(data.message)
                that.$emit('submitForm', this.dialogForm)
              } else {
                that.$message.warning(data.message)
              }
            })
            .catch((err) => {
              console.log(err)
              that.formLoading = false
            })
        }
      })
    },
    // 关闭弹窗
    handleCancel() {
      // this.resetFields()
      this.$emit('getCancel')
    },
    // 重置数据
    resetFields() {
      const that = this
      that.$nextTick(() => {
        if (that.dialogType === '添加') {
          that.$refs['dialogForm'].resetFields()// 移除表单校验并初始化表单
        } else {
          that.$refs['dialogForm'].clearValidate()// 移除表单校验
        }
      })
    },
    // 关闭弹窗，不可以删这个方法。不用这个方法点击遮罩层关闭会报错
    handleCloseBindWarnStandard() {
      // this.resetFields()
      this.$emit('closeBindWarnStandard')
    },
    handleAvatarSuccess(res, file) {
      this.dialogForm.plan = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    },
    manualPickup() {
      this.dialogVisibleMap = true
      this.$nextTick(function() {
        this.initMap()
      })
    },
    // 获取省市区
    getRegion() {
      const that = this
      getRegion()
        .then(response => {
          const data = response.data
          if (response.data.code === 40000) {
            that.options = data.data
          } else {
            that.$message.warning(data.message)
          }
        })
        .catch((err) => {
          console.log(err)
          that.formLoading = false
        })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.img-column{
  width: 50%;
  height: 118px;
  float: left;
  .el-form-item{
    width: 100%;
    float: left;
  }
}
.img-tips{
	font-size: 13px;
	font-weight: 900;
	color: #D13E3E;
}
.img-form-item{
  margin-bottom: 0px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 104px;
  height: 104px;
  line-height: 104px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon:hover{
  border-color: #409EFF;
}
.avatar {
  width: 104px;
  height: 104px;
  display: block;
}
// 地区、地址
.regionAddCombination{
  .el-cascader{
    width: 160px;
  }
  .el-input{
    width: 136px;
  }
}
// 经纬度
.mapInfo{
  position:relative;
  .el-input{
    width: 136px;
  }
  i{
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    width: 30px;
    height: 36px;
    line-height: 36px;
    text-align: center;
    font-size: 20px;
    cursor: pointer;
    -webkit-appearance: none;
    background-color: #FFF;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    -webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  }
  i:hover{
    border-color: #C0C4CC;
  }
}
.mapInfo-map{
  .el-input{
    width: 49.5%;
  }
}
#map{
  width:100%;
  height: 300px;
}
.amap-demo{
  height: 300px;
}
</style>
